import { _decorator, Component, Node, random, UITransform } from 'cc';
import { BaseWxPage } from './BaseWxPage';
import EventManager from '../../Init/Managers/EventManager';
import { EventTypes } from '../../Init/Managers/EventTypes';
import { StorageSystem } from '../../Init/SystemStorage/StorageSystem';
const { ccclass, property } = _decorator;

@ccclass('BoxPage')
export class BoxPage extends BaseWxPage {
    @property(UITransform)
    public Progress: UITransform = undefined;
    @property(Node)
    public BoxNodes: Node[] = [];

    private _clickRate: number = 0.14;
    private _autoRate: number = 0.006;
    private _errorChance: number = 0.5;
    private _progressWidth: number = 0;
    private _alreadyClick: boolean = false;

    public OnShow() {
        this._errorChance = random() * 0.4 + 0.3;
        for (var i = 0; i < this.BoxNodes.length; i++) {
            this.BoxNodes[i].active = 0 == i;
        }
        this._progressWidth = this.Progress.width;
        this.Progress.width = 0;
        this._alreadyClick = false;

        EventManager.emit(EventTypes.GameEvents.GamePause);

    }

    public OnHide() {
        // 固定获得100
        StorageSystem.setData((d) => {
            d.userAssets.asset += 500;
        }, true);
        StorageSystem.updateToAssets(false, false);
        EventManager.emit(EventTypes.GameEvents.ShowTips, '获得500金币');
        EventManager.emit(EventTypes.GameEvents.GameResume);

        for (var i = 0; i < this.BoxNodes.length; i++) {
            this.BoxNodes[i].active = 1 == i;
        }
        this.Progress.width = this._progressWidth;
    }

    public update() {
        this.Progress.width -= this._autoRate * this._progressWidth;
        if (this.Progress.width <= 0) { this.Progress.width = 0; }
        if (this.Progress.width >= this._progressWidth) { this.Progress.width = this._progressWidth; }
    }

    public OnBtnClick() {
        console.log("???")
        this.Progress.width += this._clickRate * this._progressWidth;
        if (this.Progress.width / this._progressWidth >= this._errorChance) { this.AdAction(); }
    }

    async AdAction() {
        if (this._alreadyClick) {
            return;
        }
        this._alreadyClick = true;
        // await wxsdk.GetAdById(`${this.node.name}_${this._index}`);
        this.Hide();

    }
}

